import { get,search } from "../../utils/db";
const db = wx.cloud.database()
Page({
  data: {
    lists: [],//菜谱列表
  },
  async onLoad(e) {
    let id = e.id;
    let keyword = e.keyword;    //搜索关键字
    if (id != undefined) {
      //根据分类id查询menu集合
      this.getListByTypeid(id)
    } else {

      // let result = await db.collection("menu").where({
      //   name: db.RegExp({
      //     regexp: keyword,
      //     options: "i"
      //   })
      // }).get().catch(err => console.error(err))

      let result=await search({collection:"menu",keyword:keyword}).catch(err=>{
        console.error(err)
      })
      this.setData({
        lists:result.data
      })

    }

  },
  //根据分类id查询menu集合
  async getListByTypeid(typeid) {
    //根据typeid查询menu集合
    let result = await get({ collection: "menu", typeid: typeid }).catch(err => {
      console.error(err)
    })
    result.data.forEach(item => {
      if (item.views == 0) {
        item.star = 0
      } else if (item.views > 0 && item.views <= 10) {
        item.star = 1
      } else if (item.views > 10 && item.views <= 20) {
        item.star = 2
      } else if (item.views > 20 && item.views <= 30) {
        item.star = 3
      } else if (item.views > 30 && item.views <= 40) {
        item.star = 4
      } else {
        item.star = 5
      }
    })

    //渲染数据到视图层
    this.setData({
      lists: result.data
    })
  },
  //跳转详情页
  toDetail(e) {
    let id = e.currentTarget.id;
    wx.navigateTo({
      url: '/pages/detail/detail?id=' + id,
    })
  }


})